/**
 * TodoList的意向
 */
import xs, { Stream, MemoryStream } from 'xstream';
import dropRepeats from 'xstream/extra/dropRepeats';
import { VNode, DOMSource } from '@cycle/dom';
import { HistoryDriver } from '@cycle/history';
import { Location } from 'history';
import { TodoListReducer, TodoListAction } from '../../types';
import { ENTER_KEY, ESC_KEY } from '../../../util';

export default function intent(DOM : DOMSource, history$ : MemoryStream<Location>) : TodoListAction {
    // .new-todo: 新TODO的输入框
    return {
        /**
         * 路由改变
         */
        changeRoute$: history$
            .map(location => location.pathname)
            .compose(dropRepeats()),
        /**
         * 输入框更新
         */
        updateInputValue$: DOM
            .select('.new-todo').events('input')
            .map(ev => (<HTMLInputElement>ev.target).value),
        /**
         * 输入取消
         */
        cancelInput$: DOM
            .select('.new-todo').events('keydown')
            .filter(ev => (<KeyboardEvent>ev).keyCode === ESC_KEY)
            .mapTo(null),
        /**
         * 插入Todo
         */
        insertTodo$: DOM
            .select('.new-todo').events('keydown')
            .filter((ev : KeyboardEvent) => {
                const trimmedVal = String((<HTMLInputElement>ev.target).value).trim();
                return ev.keyCode === ENTER_KEY && !!trimmedVal;
            })
            .map((ev : KeyboardEvent) => String((<HTMLInputElement>ev.target).value).trim()),
        /**
         * 切换所有
         */
        toggleAll$: DOM
            .select('.toggle-all').events('click')
            .map(ev => (<HTMLInputElement>ev.target).checked),
        /**
         * 删除完成
         */
        deleteCompleted$: DOM
            .select('.clear-completed').events('click')
            .mapTo(null)
  };

}